package com.ncmmall.mall.controller.securitys;

import com.feijin.commons.captcha.HttpCaptchaUtils;
import com.feijin.commons.lang.PropertiesHelps;
import com.google.common.collect.ImmutableList;
import nl.captcha.Captcha;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.renderer.DefaultWordRenderer;
import nl.captcha.text.renderer.WordRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @author likaikai
 * 图形验证码生成
 */
@Controller
public class CaptchaController {

    private final static Logger log = LoggerFactory.getLogger(CaptchaController.class);

    private static final List<Font> FONTS = ImmutableList.of(loadFont());

    private static final List<Color> COLORS = ImmutableList.of(Color.BLACK);
    private static final WordRenderer RENDERER = new DefaultWordRenderer(COLORS, FONTS);

    /**
     * 加载验证码字体
     */
    private static Font loadFont() {
        try {
            String fontPath = PropertiesHelps.getValue("sketchy.path");
            InputStream stream = new BufferedInputStream(new FileInputStream(fontPath));
            return Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(Font.PLAIN, 35);
        } catch (Exception e) {
            log.error("[加载字体文件异常]", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 生成图形验证码
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletRequest request, OutputStream out, @RequestParam(value = "width", defaultValue = "120") int width, @RequestParam(value = "height", defaultValue = "40") int height) {
        Captcha captcha = new Captcha.Builder(width, height).addText(RENDERER).build();
        CaptchaServletUtil.writeImage(out, captcha.getImage());
        HttpCaptchaUtils.storeCaptcha(captcha, request.getSession(true));
    }
}
